package com.ssca.mysql;

import java.io.Reader;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class ReadMysql {
	public static void readDownload(Map<String, Integer> packageDownloadNumberMap, Map<String, String> packageCategoryMap) {

		Reader reader;
		try {
			reader = Resources.getResourceAsReader("MybatisConfig.xml");
			SqlSessionFactoryBuilder ssfBuilder = new SqlSessionFactoryBuilder();
			SqlSessionFactory sqlSessionFactory = ssfBuilder.build(reader, "mysql");
			SqlSession sqlSession = sqlSessionFactory.openSession();
			DownloadNumberDAO downloadDAO = sqlSession.getMapper(DownloadNumberDAO.class);

			List<AppDownload> resultList = downloadDAO.getDownloadNumber();

			for (AppDownload info : resultList) {
				String url = info.getUrl();
				int start = url.indexOf("?id=");
				if (start != -1) {
					start += 4;
					int end;
					if ((end = url.indexOf("&feature")) == -1) {
						packageDownloadNumberMap.put(url.substring(start), info.getDownload_floor());
						packageCategoryMap.put(url.substring(start), info.getCategory());
					} else {
						packageDownloadNumberMap.put(url.substring(start, end), info.getDownload_floor());
						packageCategoryMap.put(url.substring(start, end), info.getCategory());
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
